﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Press.MVC.Services;
using Press.MVC.Data;
using System.Web.Security;

namespace Press.MVC.Web.Controllers 
{
    public class UserController : BaseController 
    {

        public class UserData 
        {
            public string LoginMessage { get; set; }
            public User User { get; set; }
            public Blog Blog { get; set; }
            public string RegistrationMessage { get; set; }
            public string BlogAlreadyExistsMessage { get; set; }
            public bool isMtaAdmin { get; set; }
            public UserData() 
            {
                this.User = new User();
                this.Blog = new Blog();
            }

        }

        IUserService _userService;
        IBlogService _blogService;


        public UserController(IUserService userService, IBlogService blogService) 
        {
            _userService = userService;
            _blogService = blogService;
        }

        public ActionResult Index()
        {
            // Add action logic here
            return RedirectToAction("Login");
        }

        public ActionResult Login()
        {
            UserData data = new UserData();

            if (TempData["loginmessage"] != null)
                data.LoginMessage = TempData["loginmessage"].ToString();

            return View("Login", data);

        }

        public ActionResult Authenticate()
        {
            string login = this.ReadFromRequest("username");
            string password = this.ReadFromRequest("password");

            UserData data = new UserData();
            data.LoginMessage = "You must specify a username and password.";
            if (!String.IsNullOrEmpty(login) && !String.IsNullOrEmpty(password))
            {
                var svc = new AspnetAuthenticationService();
                bool isValid = svc.IsValidLogin(login, password);

                //log them in 
                if (isValid)
                {
                    SetPersonalizationCookie(login);
                    return SetAuthCookieAndRedirect(login);
                }
                else
                {
                    data.LoginMessage = "Invalid login";
                }
            }
            return View("Login",data);
        }        

        ActionResult SetAuthCookieAndRedirect(string userName)
        {

            string returnUrl = this.ReadFromRequest("ReturnUrl");
            FormsAuthentication.SetAuthCookie(userName, false);

            if (!String.IsNullOrEmpty(returnUrl))
            {

                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Blog");
            }
        }

        void SetPersonalizationCookie(string userName)
        {
            Response.Cookies["shopper"].Value = userName;
            Response.Cookies["shopper"].Expires = DateTime.Now.AddDays(30);            
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Home");

        }

        public ActionResult Register() {

            UserData data = new UserData();

            if (TempData["userdata"] != null)
                data = (UserData)TempData["userdata"];
             

            return View("Register",data);
        }

        public ActionResult Create() 
        {

            UserData data = new UserData();
            data.User.Email = this.ReadFromRequest("Email");
            data.User.FirstName = this.ReadFromRequest("First");
            data.User.LastName = this.ReadFromRequest("Last");
            data.User.UserName = this.ReadFromRequest("Login");

            string userName = this.ReadFromRequest("login");
            string password = this.ReadFromRequest("password");
            string confirm = this.ReadFromRequest("confirm");
            string question = this.ReadFromRequest("question");
            string answer = this.ReadFromRequest("answer");


            // Check if the user entered blog exists based on the short name
            bool doesBlogExist = false;

            data.Blog.Name = this.ReadFromRequest("Title");
            data.Blog.ShortName = this.ReadFromRequest("ShortName");
            
            // A blog is set in active until the blog is activated through the Blog Activation email sent to the user account email address below.
            data.Blog.IsActive = false;

            string shortName = this.ReadFromRequest("ShortName");
            Blog b = _blogService.GetBlog(shortName);
            if (b != null)
            {
                // TODO store strings in Resource Manager that are localized per language.
                // TODO write Resource Manager
                data.BlogAlreadyExistsMessage = String.Format("The Blog with a short name '{0}' already exists, please enter another name.", shortName);
                TempData["userdata"] = data;
                return RedirectToAction("Register");
            }
            else 
            {
                // If it doesn't exist then create the blog
                
                _blogService.SaveBlog(data.Blog);           
           
                string returnUrl = this.ReadFromRequest("ReturnUrl");
                // Create the Membership user
                try
                {
                    _userService.RegisterUser(data.User.UserName, password, confirm, data.User.Email, question, answer);

                    //Log the user into the system
                    FormsAuthentication.SetAuthCookie(data.User.UserName, false);

                    // Send the Blog Activation email. 
                    // TODO store the email in a Resource template.

                    // Send the user to the Blog needs Activation Page in the Blog Controller
                    return RedirectToAction("BlogActivationRequired", "Blog");
                }
                catch (InvalidOperationException x)
                {
                    //catch and release
                    data.RegistrationMessage = x.Message;
                    TempData["userdata"] = data;
                    return RedirectToAction("Register");
                }          
            
            }
                

                
        }

        public ActionResult ShowUserSummary()
        {
            UserData udata = new UserData();
            udata.User = _userService.GetUser(AppHelper.GetUserName());
            Press.MVC.Services.AspNetAuthorizationService svc = new Press.MVC.Services.AspNetAuthorizationService();
            string isAdmin = svc.IsMtaAdmin(AppHelper.GetUserName()).ToString();
            udata.isMtaAdmin = svc.IsMtaAdmin(AppHelper.GetUserName());
            ViewData["HasPermission"] = isAdmin;

            return View("UserAccountSummary", udata);
        }    

    }
}
